package com.rookie.shiro.module.config;

import com.rookie.shiro.module.config.security.ShiroSecurity;
import com.rookie.shiro.module.constant.ErrorEnum;
import com.rookie.shiro.module.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * @author rookie
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private Map<String, ShiroSecurity> map;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Token;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        List<String> permList = null;

        String token = TokenUtils.getToken();
//        选择权限
        for (String key : map.keySet()) {
            if (map.get(key).supports(token)){
                permList = map.get(key).getUserPermission(token);
                break;
            }
        }
        simpleAuthorizationInfo.addStringPermissions(permList);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String nullString = "null";
        String token = (String) authenticationToken.getCredentials();
        if (token == null || nullString.equals(token)) {
            throw new IncorrectCredentialsException(ErrorEnum.E_30003.getErrorMsg());
        }
        //        选择权限
        for (String key : map.keySet()) {
            if (map.get(key).supports(token)){
                map.get(key).doGetAuthentication(token);
                break;
            }
        }
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
